//
//  LeftViewController.m
//  ZhiHuDaily
//
//  Created by albert on 16/8/14.
//  Copyright © 2016年 albert. All rights reserved.
//

#import "LeftViewController.h"
#import "NetworkingTool.h"
#import "ThemesModel.h"
#import <MJExtension/MJExtension.h>
#import "UIImage+JKExtension.h"
#import "Reachability.h"
#import "JKProgressHUD.h"
#import "SQLiteManager.h"
#import "NewsListGetDataModel.h"

@interface LeftViewController () <UITableViewDataSource, UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;

/** 头像 */
@property (weak, nonatomic) IBOutlet UIImageView *iconImageView;

/** 切换皮肤按钮 */
@property (weak, nonatomic) IBOutlet UIButton *updateSkinButton;

/** 昵称 */
@property (weak, nonatomic) IBOutlet UIButton *nameButton;

/** 离线下载按钮 */
@property (weak, nonatomic) IBOutlet UIButton *downLoadToLocaleBtn;

/** 离线下载进度条 */
@property (weak, nonatomic) IBOutlet UILabel *progressLabel;

/** 主题模型 */
@property (nonatomic, strong) NSArray *themeModels;

/** 主题 */
@property (nonatomic, strong) NSArray *themes;

/** 重新加载按钮 */
@property (nonatomic, weak) UIButton *reloadBtn;

/** 网络状态检测 */
@property (nonatomic, strong) Reachability *reach;

/** 当前皮肤模式 */
@property (nonatomic, copy) NSString *currentSkinModel;
@end

@implementation LeftViewController

#pragma mark - 懒加载
- (UIButton *)reloadBtn{
    if (!_reloadBtn) {
        UIButton *reloadBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        reloadBtn.titleLabel.numberOfLines = 0;
        reloadBtn.titleLabel.font = [UIFont systemFontOfSize:12];
        reloadBtn.hidden = YES;
        reloadBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [reloadBtn setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
        [reloadBtn setTitle:@"点击此处刷新主题列表" forState:(UIControlStateNormal)];
        [reloadBtn addTarget:self action:@selector(loadData) forControlEvents:(UIControlEventTouchUpInside)];
        self.tableView.tableFooterView = reloadBtn;
        [self.tableView addSubview:reloadBtn];
        _reloadBtn = reloadBtn;
    }
    return _reloadBtn;
}

#pragma mark - 生命周期方法
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.currentSkinModel = [[NSUserDefaults standardUserDefaults] objectForKey:JKCurrentSkinModelKey];
    self.updateSkinButton.selected = [self.currentSkinModel isEqualToString:JKNightSkinModelValue] ? YES : NO;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceDidShake:) name:JKDeviceDidShakeNotification object:nil];
    
    [self updateUserIconAndName];
}

- (void)deviceDidShake:(NSNotification *)noti{
    self.currentSkinModel = [[NSUserDefaults standardUserDefaults] objectForKey:JKCurrentSkinModelKey];
    self.updateSkinButton.selected = [self.currentSkinModel isEqualToString:JKNightSkinModelValue] ? YES : NO;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:JKSkinModelDidChangedNotification object:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor colorWithRed:26/255.0 green:31/255.0 blue:36/255.0 alpha:1];
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 30, 0);
    
    self.tableView.backgroundColor = [UIColor colorWithRed:26/255.0 green:31/255.0 blue:36/255.0 alpha:1];
    
    [self updateUserIconAndName];
    
    [self loadData];
}

- (void)loadData{
    [[NetworkingTool sharedNetworkingTool] loadDataWithUrl:@"themes" parameters:nil finishedBlock:^(id responseObj, NSError *error) {
        
        if (error) {
            self.reloadBtn.hidden = NO;
            return;
        }
        
        self.themeModels = [ThemesModel mj_objectArrayWithKeyValuesArray:responseObj[@"others"]];
        self.themes = [self.themeModels valueForKeyPath:@"name"];
        [self.tableView reloadData];
        
        self.reloadBtn.hidden = (self.themeModels.count > 2);
        
        [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] animated:NO scrollPosition:(UITableViewScrollPositionNone)];
    }];
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.reloadBtn.frame = CGRectMake(20, (self.tableView.height - 60) * 0.5, self.tableView.width - 40, 60);
}

#pragma mark - <UITableViewDataSource>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (!self.themes) {
        return 2;
    }
    return self.themes.count + 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"cell"];
    }
    
    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.textColor = [UIColor whiteColor];
    UIView *selectBkView = [[UIView alloc] init];
    selectBkView.backgroundColor = [UIColor colorWithRed:11/255.0 green:16/255.0 blue:20/255.0 alpha:1];
    cell.selectedBackgroundView = selectBkView;
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    if (indexPath.row == 0) {
        cell.textLabel.text = @"首页";
    }else if (indexPath.row == 1){
        cell.textLabel.text = @"专栏";
    }else{
        cell.textLabel.text = self.themes[indexPath.row-2];
    }
    
    return cell;
}

#pragma mark - <UITableViewDelegate>
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ThemesModel *model = nil;
    
    if (indexPath.row > 1) {
        model = self.themeModels[indexPath.row - 2];
    }
    
    !self.cellSelectedBlock ? : self.cellSelectedBlock(model, indexPath.row);
}

#pragma mark - 点击事件
- (IBAction)settingBtnClick:(id)sender {
    [self.tableView reloadData];
    !self.settingBtnBlock ? : self.settingBtnBlock();
}
- (IBAction)iconClick:(id)sender {
    [self.tableView reloadData];
    !self.iconBtnBlock ? : self.iconBtnBlock();
}

- (IBAction)collectionBtnClick:(id)sender {
    [self.tableView reloadData];
    !self.collectionBtnBlock ? : self.collectionBtnBlock();
}

- (IBAction)messageBtnClick:(id)sender {
    [self.tableView reloadData];
    !self.messageBtnBlock ? : self.messageBtnBlock();
}

- (IBAction)downLoadToLocaleBtnClick:(id)sender {
    self.reach = [Reachability reachabilityWithHostName:@"baidu.com"];
    
    if (self.reach.currentReachabilityStatus == NotReachable) {
        [JKProgressHUD showErrorWithStatus:@"您的网络貌似优点问题哦~"];
        return;
    }
    
    if (self.reach.currentReachabilityStatus == ReachableViaWWAN) {
        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"提示" message:@"当前处于移动网络，确定要离线下载吗？" preferredStyle:(UIAlertControllerStyleAlert)];
        
        [alertVc addAction:[UIAlertAction actionWithTitle:@"流量多，不怕！" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            [self downLoadToLocale];
        }]];
        
        [alertVc addAction:[UIAlertAction actionWithTitle:@"还是算了吧~~" style:(UIAlertActionStyleCancel) handler:nil]];
        
        [self presentViewController:alertVc animated:YES completion:nil];
        return;
    }
    [self downLoadToLocale];
}

// 开始离线下载
- (void)downLoadToLocale{
    self.downLoadToLocaleBtn.userInteractionEnabled = NO;
    self.progressLabel.hidden = NO;
    self.progressLabel.text = @"0%";
    
    [NewsListGetDataModel loadLatestDatafWithFinishedBlock:^(NSDictionary *dict, NSError *error) {
        NSArray *latestListIDs = [dict[JKStoryListKey] valueForKeyPath:@"ID"];
        NSArray *topStoriesIDs = [dict[JKTopStoryListKey] valueForKeyPath:@"id"];
        NSMutableArray *IDs = [NSMutableArray array];
        
        [IDs addObjectsFromArray:topStoriesIDs];
        [IDs addObjectsFromArray:latestListIDs];
        
        [SQLiteManager cacheDetailWithIDs:IDs];
    }];
    
    __weak typeof(self) weakSelf = self;
    [[SQLiteManager sharedmanager] setCacheCompletedBlock:^(NSString *progressText) {
        
        weakSelf.progressLabel.text = progressText;
        
        if ([progressText isEqualToString:@"100%"]) {
            [UIView animateWithDuration:0.5 delay:0.5 options:0 animations:^{
                weakSelf.progressLabel.alpha = 0;
            } completion:^(BOOL finished) {
                weakSelf.downLoadToLocaleBtn.userInteractionEnabled = YES;
                weakSelf.progressLabel.hidden = YES;
                weakSelf.progressLabel.alpha = 1;
            }];
        }
    }];
}

// 切换皮肤，发送通知
- (IBAction)updateSkin:(UIButton *)sender {
    sender.selected = !sender.selected;
    
    NSString *skinValue = (sender.selected) ? JKNightSkinModelValue : JKDaySkinModelValue;
    
    [[NSUserDefaults standardUserDefaults] setObject:skinValue forKey:JKCurrentSkinModelKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:JKSkinModelDidChangedNotification object:self];
}

// 更新用户名和头像
- (void)updateUserIconAndName{
    NSString *name = [[NSUserDefaults standardUserDefaults] objectForKey:JKUserNameKey];
    [self.nameButton setTitle:name forState:(UIControlStateNormal)];
    
    if (![[NSUserDefaults standardUserDefaults] boolForKey:JKIsLoginKey]) {
        self.iconImageView.image = [[UIImage imageNamed:@"Setting_Avatar"] circleImage];
        return;
    }
    
    NSString *imgPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"userIcon.png"];
    UIImage *img = [UIImage imageWithContentsOfFile:imgPath];
    if (img == nil) {
        img = [UIImage imageNamed:@"myIcon"];
    }
    self.iconImageView.image = [img circleImage];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
